package com.ruoyi.common.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Enumeration;

@Component
@ServerEndpoint("/arcus/flask/monitor/websocket/{uuid}")  // ws://localhost:40001/arcus/flask/monitor/websocket
public class FlaskWebSocket implements IWebSocket{
    private static final Logger log = LoggerFactory.getLogger(FlaskWebSocket.class);

    private String uuid;
    private Session session;

    @Override
    public void push(String msg) {
        try {
            this.session.getBasicRemote().sendText(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void push(String uuid, String msg) {

    }

    @OnMessage
    @Override
    public void msgArriveDefault(String msg) {
        log.info("arrive msg： " + msg);
        this.push("I have received this msg: " + msg);
    }

    @OnError
    @Override
    public void msgSendError(Session session, Throwable error) {
        log.error("错误");
    }

    public void printSessionInfo(){
        log.info("A new calculate module connect, details is: ");
        log.info("  -- session id is: " + session.getId());
        log.info("  -- protocol version is: " + session.getProtocolVersion());
        log.info("  -- request uri is: " + session.getRequestURI().toString());
        log.info("  -- device uuid is: " + uuid);
        log.info("  -- on line calculate module number is: " + IWebSocket.socketMap.size());

    }

    private void closeSession(String uuid) throws IOException {
        FlaskWebSocket socketInstance = (FlaskWebSocket) IWebSocket.socketMap.get(uuid);
        socketInstance.session.close();
    }

    @OnOpen
    @Override
    public void connect(Session session, @PathParam(value = "uuid") String uuid) {
        this.uuid = uuid;
        this.session = session;

        // 重新链接的时候会创建新的session，应该关闭旧的session
        if(IWebSocket.socketMap.containsKey(uuid)){
            log.info("A device try to re-connect, try to close session before");
            try {
                this.closeSession(uuid);
            }catch (Exception e){
                e.printStackTrace();
            }
            IWebSocket.socketMap.put(uuid, this);
            log.info("Device " + uuid + "now re-connect success");
        }else{
            IWebSocket.socketMap.put(uuid, this);
        }

        this.printSessionInfo();
    }

    @OnClose
    @Override
    public void disConnect() {
        IWebSocket.socketMap.remove(this.uuid);
        log.warn("A calculate module has dis-connect, please check device is running.");
        log.warn("  -- device uuid is: " + this.uuid);
        log.warn("  -- on line calculate module number is: " + IWebSocket.socketMap.size());
    }
}
